package com.zyc.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zyc.eduservice.entity.EduSubject;
import com.zyc.eduservice.entity.excel.SubjectData;
import com.zyc.eduservice.entity.excel.SubjectListener;
import com.zyc.eduservice.entity.subject.OneSubject;
import com.zyc.eduservice.entity.subject.TwoSubject;
import com.zyc.eduservice.mapper.EduSubjectMapper;
import com.zyc.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyc.exception.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-02-17
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Autowired
    private EduSubjectService eduSubjectService;

    @Override
    public void saveSubject(MultipartFile file,EduSubjectService eduSubjectService) {
        try {
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, SubjectData.class,new SubjectListener(eduSubjectService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            throw new GuliException(20002,"添加课程分类失败");
        }

    }

    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        List<OneSubject> oneSubjectList = new ArrayList<>();

        QueryWrapper<EduSubject> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("parent_id","0");
        List<EduSubject> oneList = baseMapper.selectList(wrapper1);

        QueryWrapper<EduSubject> wrapper2 = new QueryWrapper<>();
        wrapper2.ne("parent_id", "0");
        List<EduSubject> twoList = baseMapper.selectList(wrapper2);

        // 封装一级
        for (EduSubject one : oneList) {
            OneSubject oneSubject = new OneSubject();
            oneSubject.setId(one.getId());
            oneSubject.setTitle(one.getTitle());
            oneSubjectList.add(oneSubject);
        }

        // 封装二级
        for (OneSubject oneSubject : oneSubjectList) {
            List<TwoSubject> twoSubjectList = new ArrayList<>();
            for (EduSubject two : twoList) {
                if (two.getParentId().equals(oneSubject.getId())) {
                    TwoSubject twoSubject = new TwoSubject();
                    twoSubject.setId(two.getId());
                    twoSubject.setTitle(two.getTitle());
                    twoSubjectList.add(twoSubject);
                }
                oneSubject.setTwoSubjectList(twoSubjectList);
            }
        }
        return oneSubjectList;
    }
}
